<?php

namespace App\Jobs;

use App\Helpers\NewBaseData;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;
use App\Models\Car;
use App\Models\Car\CarUsedDate;
use Illuminate\Support\Facades\DB;

class CreateCarUsedDate implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    protected $order;
    public function __construct()
    {
        //
       // $this->order = $order;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        // info('开始执行车系日历生成');
        $carlist = Car::query()->get();
        $year = date('Y');
        $month = date('m');
        $day = date('d');
        if(count($carlist)>0){
            foreach ($carlist as $item){
                // 找到对应车系，当前年份是否有记录，如果没有记录，就生成今年的记录
                $usedlist = CarUsedDate::query()->where('car_id',$item->id)->where('year',$year)->get();
                if(count($usedlist)==0){
                    $this->createYearDate($item->id, $year);
                }
            }
        }
        // 把所有当前日期之外的数据更新为已占用
        CarUsedDate::query()->where(function ($query) use($year,$month) {
            $query->where('year','<=',$year)->where('month','<',$month);
        })->orWhere(function ($query) use($year,$month,$day) {
            $query->where('year','<=',$year)->where('month','<=',$month)->where('day','<',$day);
        })->update(['is_used'=>2]);
    }
    // 按车系id和年份，生成一年的日历
    protected function createYearDate($id, $year){
        // 处理逻辑
        $data = [];
        for ($i=1; $i <= 12; $i++) {
            $date = new \DateTime("$year-$i-01");
            $daysInMonth = $date->format("t");
            for ($j=1; $j <= $daysInMonth; $j++) {
                $ii = $i<10?'0'.$i:$i;
                $jj = $j<10?'0'.$j:$j;
                $data[]= [
                    'car_id'=> $id,
                    'year'=> $year,
                    'month'=> $i,
                    'day'=>$j,
                    'time'=>$year.$ii.$jj
                ];
            }
        }
        // info(is_string($data)?$data:json_encode($data));
        if(count($data)>0){
            DB::table('car_used_dates')->insert($data);
        }
    }
}
